package com.asggo.g21.filter;

import com.asggo.g21.wrapper.CachedBodyHttpServletRequest;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.http.MediaType;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.multipart.MultipartResolver;

/**
 * Created by IntelliJ IDEA.
 *
 * @author eric 2022/8/11 10:14
 */
@Component
public class MultiReadRequestFilter extends OncePerRequestFilter {

  private final MultipartResolver multipartResolver;

  public MultiReadRequestFilter(MultipartResolver multipartResolver) {
    this.multipartResolver = multipartResolver;
  }

  @Override
  protected void doFilterInternal(HttpServletRequest request,
      @NonNull HttpServletResponse response,
      @NonNull FilterChain filterChain) throws ServletException, IOException {
    String contentType = request.getContentType();
    if (contentType != null && contentType.contains(MediaType.MULTIPART_FORM_DATA_VALUE)) {
      request = multipartResolver.resolveMultipart(request);
    }
    CachedBodyHttpServletRequest cachedBodyHttpServletRequest =
        new CachedBodyHttpServletRequest(request);

    filterChain.doFilter(cachedBodyHttpServletRequest, response);
  }
}
